import axios from 'axios'

const instance = axios.create({
  timeout: '60000',
  headers: {
    'Content-Type': 'application/json',
  },
})

instance.interceptors.request.use(
  (config) => {
    const planType = localStorage.getItem('planType') || '1'
    config.headers.Type = planType
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  (response) => {
    if (response) {
      return Promise.resolve(response.data)
    }
  },
  (error) => {
    console.log(error)
    return Promise.reject(error)
  }
)

export function getHttpService(HttpRequest) {
  let httpObj = {}
  for (let [key, value] of Object.entries(HttpRequest)) {
    let { url, method } = value
    httpObj[key] = (params, cb, config = {}) => {
      let requestParams = paramsHandleObj[method](params)
      let requestUrl = cb ? cb(url) : url
      return new Promise((resolve, reject) => {
        instance[method](requestUrl, requestParams, config)
          .then((res) => {
            resolve(res)
          })
          .catch((err) => reject(err))
      })
    }
  }
  return httpObj
}

const paramsHandleObj = {
  get(params) {
    return { params }
  },
  post(params) {
    return params
  },
  delete(params) {
    return { params }
  },
  put(params) {
    return params
  },
}

export default instance
